<template>
  <input
    type="checkbox"
    :value="value"
    :class="cn(checkboxVariants({ color, size }), $attrs.class)"
    :checked="Array.isArray(model) ? model.includes(value) : value"
    @change="onChange"
  />
</template>
<script setup lang="ts">
import { cva } from "class-variance-authority";
import { cn } from "../utils";

import type { CheckboxColor } from "./types";
import type { Size } from "../ui/types";

const checkboxVariants = cva("checkbox", {
  variants: {
    color: {
      primary: "checkbox-primary",
      secondary: "checkbox-secondary",
      accent: "checkbox-accent",
      neutral: "checkbox-neutral",
      success: "checkbox-success",
      warning: "checkbox-warning",
      info: "checkbox-info",
      error: "checkbox-error",
    },
    size: {
      xs: "checkbox-xs",
      sm: "checkbox-sm",
      md: "checkbox-md",
      lg: "checkbox-lg",
      xl: "checkbox-xl",
    },
  },
  defaultVariants: {},
});

interface Props {
  color?: CheckboxColor;
  size?: Size;
  value?: any;
  checked?: boolean;
}
const props = defineProps<Props>();

const model = defineModel<Array<any> | boolean>();
function onChange(event: Event) {
  if (Array.isArray(model.value)) {
    if ((event.target as HTMLInputElement).checked)
      model.value = [...model.value, props.value];
    else model.value = model.value.filter((i) => i != props.value);
  } else model.value = (event.target as HTMLInputElement).checked;
}
</script>
